<template>
    <div class="container">

        <div class="aside" style="display: flex;flex-direction: column;justify-content: space-between;">
            <el-card>
                <template #header>
                    <div class="card-header">
                        <b> 文章点赞（{{ userInfo.likes.length }}）</b>
                    </div>
                </template>
                <el-table :data="userInfo.likes" style="width: 100%" border>
                    <el-table-column label="标题" align="center">
                        <template #default="scope">
                            <el-button type="primary" link @click="toArticleDetail(scope.row.id)">{{ scope.row.title || '暂无'
                            }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="点赞数" align="center">
                        <template #default="scope">
                            <span>{{ scope.row.liker.length }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
            <el-card class="aside">
                <template #header>
                    <div class="card-header">
                        <b> 评论点赞（{{ userInfo.commentLikes.length }}）</b>
                    </div>
                </template>
                <el-table :data="userInfo.commentLikes" style="width: 100%" border>
                    <el-table-column label="内容" align="center">
                        <template #default="scope">
                            <el-button type="primary" link @click="toArticleDetail(scope.row.article.id)">{{
                                scope.row.content || '暂无'
                            }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="作者" align="center">
                        <template #default="scope">
                            <span>{{ scope.row.author }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </el-card>
        </div>
        <div class="main-container">
            <el-card class="box-card">
                <template #header>
                    <div class="card-header">
                        <h2>个人信息</h2>
                        <el-button class="button" type="primary" @click="updateUserInfo">修改信息</el-button>
                    </div>
                </template>
                <div class="text avatar-container">头像：
                    <img class="img" :src="userInfo.avatar || logo">
                </div>
                <div class="text item">昵称：{{ userInfo.nickname || '暂无' }}</div>
                <div class="text item">性别：{{ userInfo.gender || '暂无' }}</div>
                <div class="text item">生日：{{ (userInfo.birthday && dayForMat(userInfo.birthday, 'YYYY/MM/DD')) || '暂无' }}
                </div>
                <div class="text item">邮箱：{{ userInfo.email || '暂无' }}</div>
                <div class="text item">电话：{{ userInfo.phone || '暂无' }}</div>
                <div class="text item">地址：{{ userInfo.address || '暂无' }}</div>
                <div class="text item">简介：{{ userInfo.introduction || '暂无' }}</div>
                <div class="text item">爱好：
                    <el-tag v-for="tag in userInfo.hobbies" :key="tag.id" class="mx-1" type="success"
                        :disable-transitions="false">
                        {{ tag.name }}
                    </el-tag>
                </div>
                <div class="text item">职业：{{ userInfo.profession || '暂无' }}</div>
            </el-card>
            <el-card >
                <el-button type="danger" class="edit-btn" @click="accountDrawer = true">修改密码</el-button>
            </el-card>
        </div>

        <div class="aside" style="display: flex;flex-direction: column;justify-content: space-between;">
            <el-card>
                <template #header>
                    <b>关注/粉丝</b>
                </template>
                <div style="display: flex;flex-direction: column; align-items: center;">
                    <el-avatar :size="40" :src="userInfo.avatar || logo"></el-avatar>
                    <div style=" display: flex; justify-content: space-evenly; padding: 10px 0;">
                        <el-popover placement="bottom" :width="200" trigger="click">
                            <template #reference>
                                <el-button type="warning" link> 关注数：{{ userInfo.followings.length }} </el-button>
                            </template>
                            <el-table :data="userInfo.followings">
                                <el-table-column property="nickname" label="昵称" />
                                <el-table-column property="avatar" label="头像">
                                    <template #default="scope">
                                        <el-avatar :size="40" :src="scope.row.avatar || logo"></el-avatar>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-popover>
                        <el-popover placement="bottom" :width="200" trigger="click">
                            <template #reference>
                                <el-button type="warning" link>粉丝数：{{ userInfo.follower.length }}</el-button>
                            </template>
                            <el-table :data="userInfo.follower" empty-text="暂无关注">
                                <el-table-column property="nickname" label="昵称" />
                                <el-table-column property="avatar" label="头像">
                                    <template #default="scope">
                                        <el-avatar :size="40" :src="scope.row.avatar || logo"></el-avatar>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-popover>
                    </div>
                </div>
            </el-card>
            <el-card class="aside">
                <template #header>
                    <div class="card-header">
                        <b> 站长推荐</b>
                        <el-tooltip content="查看更多" placement="right"><el-button link type="primary"
                                @click="router.push({ name: 'home' })">更多</el-button></el-tooltip>
                    </div>
                </template>
                <el-table :data="tableInfo.articles" style="width: 100%" border>
                    <el-table-column prop="title" label="标题" align="center">
                        <template #default="scope">
                            <el-tooltip :content="`${scope.row.title}`" placement="top">
                                <el-button type="primary" link @click="toArticleDetail(scope.row.id)">{{ scope.row.title }}
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="作者" align="center">
                        <template #default="scope">
                            <span>{{ scope.row.author }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="简介" align="center">
                        <template #default="scope">
                          <div class="introduction-box">
                            <span>{{ scope.row.introduction }}</span>
                          </div> 
                        </template>
                    </el-table-column>
                </el-table>
                <el-radio-group v-model="tableInfo.orderDto.sort" @change="initTableInfo()">
                    <el-radio label="liker">点赞数</el-radio>
                    <el-radio label="beCollected">收藏数</el-radio>
                    <el-radio label="viewer">浏览数</el-radio>
                    <el-radio label="comment">评论数</el-radio>
                </el-radio-group>
                <el-switch v-model="tableInfo.orderDto.order" class="mb-2" active-value="DESC" inactive-value="ASC"
                    style="--el-switch-on-color:#ff4949; --el-switch-off-color:#13ce66" active-text="降序" inactive-text="升序"
                    @change="initTableInfo()" />
                <!-- <el-radio-group v-model="tableInfo.orderDto.order" @change="initTableInfo()">
                <el-radio-button label="DESC" size="large" border>降序</el-radio-button>
                <el-radio-button label="ASC" size="large" border>升序</el-radio-button>
            </el-radio-group> -->
            </el-card>
        </div>


    </div>
    <!-- 修改账户的抽屉 -->
    <el-drawer v-model="accountDrawer">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">账户信息</h4>
        </template>
        <el-form ref="registerFormRef" :model="updateAccountForm" label-width="80px" :rules="rules" class="loginForm">
            <el-form-item prop="oldPassword" label="原密码">
                <el-input v-model.trim="updateAccountForm.oldPassword" type="password" show-password clearable />
            </el-form-item>
            <el-form-item prop="newPassword" label="新密码">
                <el-input v-model.trim="updateAccountForm.newPassword" type="password" show-password clearable />
            </el-form-item>
            <el-form-item prop="sNewPassword" label="确定密码">
                <el-input v-model.trim="updateAccountForm.sNewPassword" type="password" show-password clearable />
            </el-form-item>
            <el-form-item>
                <div class="account-btn-container">
                    <el-button @click="cancelUpdateAccount(registerFormRef)">取消</el-button>
                    <el-button type="primary" @click="updateAccount(registerFormRef)">修改</el-button>
                </div>
            </el-form-item>
        </el-form>
    </el-drawer>


    <el-dialog v-model="dialogFormVisible" title="个人信息" width="600px">
        <el-form :model="updateUserInfoForm" ref="updateUserInfoFormRef" :rules="rules">
            <el-form-item label="头像：" :label-width="formLabelWidth">
                <el-upload class="avatar-uploader" :http-request="(options: any) => upload(options, uploadIcon)"
                    :show-file-list="false" :before-upload="beforeAvatarUpload">
                    <!-- :on-success="handleAvatarSuccess"  -->
                    <img v-if="updateUserInfoForm.avatar" :src="updateUserInfoForm.avatar" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="昵称：" :label-width="formLabelWidth">
                <el-input v-model="updateUserInfoForm.nickname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别：" :label-width="formLabelWidth">
                <el-select v-model="updateUserInfoForm.gender" placeholder="--请选择--">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                    <el-option label="保密" value="保密" />
                </el-select>
            </el-form-item>
            <el-form-item label="生日：" :label-width="formLabelWidth">
                <div class="block">
                    <el-date-picker v-model="updateUserInfoForm.birthday" type="date" placeholder="Pick a date"
                        format="YYYY/MM/DD" :default-value="new Date(2000, 0, 0)" />
                </div>
            </el-form-item>
            <el-form-item label="邮箱：" :label-width="formLabelWidth" prop="email">
                <el-input v-model="updateUserInfoForm.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话：" :label-width="formLabelWidth" prop="phone">
                <el-input v-model="updateUserInfoForm.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="地址：" :label-width="formLabelWidth" prop="address">
                <el-input v-model="updateUserInfoForm.address" autocomplete="off" />
            </el-form-item>
            <el-form-item label="简介：" :label-width="formLabelWidth">
                <el-input v-model="updateUserInfoForm.introduction" :rows="2" type="textarea" autocomplete="off" />
            </el-form-item>
            <el-form-item label="爱好：" :label-width="formLabelWidth">
                <el-tag v-for="tag in updateUserInfoForm.hobbies" :key="tag" class="mx-1" closable type="success"
                    :disable-transitions="false" @close="handleClose(tag)">
                    {{ tag }}
                </el-tag>
                <el-input v-if="updateUserInfoForm.inputVisible" ref="InputRef" v-model="updateUserInfoForm.inputValue"
                    class="ml-1 w-20" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                    + New Tag
                </el-button>
            </el-form-item>
            <el-form-item label="职业：" :label-width="formLabelWidth">
                <el-input v-model="updateUserInfoForm.profession" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submitSaveUserInfo(updateUserInfoFormRef)">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template> 
<script name="Personal"  setup lang='ts' >
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElButton, ElDrawer, ElMessage, type FormInstance, type FormRules, type TabsPaneContext, ElInput, type UploadRequestOptions, ElNotification, } from 'element-plus'
import type { UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserInfoStore } from '@/stores'
import { dayForMat } from '@/utils'
import { editAccount, editUserInfo, upload, findArticles, findAccount } from '@/api'
import { useRouter } from 'vue-router'
import { toReactive } from '@vueuse/shared';
import logo from '@/assets/images/logo.jpg'
const router = useRouter()
const userInfoStore = useUserInfoStore()
const { uuid } = userInfoStore.userInfo
interface updateAccountForm {
    oldPassword: string,
    newPassword: string,
    sNewPassword: string
}
interface UserInfo {
    user_id: number,
    avatar: string,
    uuid: string,
    account: string,
    nickname: string,
    gender: '男' | '女' | '保密',
    birthday: string,
    email: string,
    phone: string,
    address: string,
    introduction?: string,
    hobbies: Array<any>,
    profession: string,
    create_time: string,
    likes: Array<any>,
    commentLikes: Array<any>,
    followings: Array<{ avatar: string, uuid: string, nickname: string }>,
    follower: Array<{ avatar: string, uuid: string, nickname: string }>

} 
interface UpdateUserInfoForm {
    uuid: string,
    avatar: string,
    nickname: string,
    gender: '男' | '女' | '保密',
    birthday: string,
    email: string,
    phone: string,
    address: string,
    introduction?: string,
    hobbies: Array<any>,
    profession: string,
    inputValue: string,
    inputVisible: boolean,
}

interface TableInfo {
    articles: Array<any>,
    limit: number,
    orderDto: {
        sort: string,
        order: 'ASC' | 'DESC'
    },
    total: number
}

const tableInfo = reactive<TableInfo>({
    articles: [],
    limit: 6,
    total: 0,
    orderDto: {
        sort: 'liker',
        order: "DESC"
    }
})


const accountDrawer = ref(false)
const registerFormRef = ref<FormInstance>()
const updateUserInfoFormRef = ref<FormInstance>()
let updateUserInfoForm = <UpdateUserInfoForm>{
    uuid: '',
    avatar: '',
    //用户昵称
    nickname: '',
    //用户性别  
    gender: '保密',
    //用户生日
    birthday: '',
    //用户邮箱 
    email: '',
    //用户手机号
    phone: '',
    //用户地址
    address: '',
    //用户个人简介
    introduction: '',
    //用户爱好 
    hobbies: [],
    //用户职业
    profession: '',
    inputValue: '',
    inputVisible: false,

}
const dialogFormVisible = ref(false)
const formLabelWidth = '80px'

const InputRef = ref<InstanceType<typeof ElInput>>()

const userInfo = ref<UserInfo>({
    user_id: 0,
    avatar: '',
    account: '',
    uuid: '',
    //用户昵称
    nickname: '',
    //用户性别  
    gender: '保密',
    //用户生日
    birthday: '',
    //用户邮箱 
    email: '',
    //用户手机号
    phone: '',
    //用户地址
    address: '',
    //用户个人简介
    introduction: '',
    //用户爱好  
    hobbies: [],
    //用户职业
    profession: '',
    create_time: '',
    likes: [],
    commentLikes: [],
    follower: [],
    followings: []
})

const rules = reactive<FormRules>({
    oldPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 12, message: '长度为6-12个字符', trigger: 'blur' },
        { pattern: /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![!<>#$?@%^&*,]+$)[\da-zA-Z!<>#$?@%^&*,]{6,12}$/, message: '至少包含大小写字母、数字和特殊字符其中两种', trigger: 'blur' }

    ],
    newPassword: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 12, message: '长度为6-12个字符', trigger: 'blur' },
        { pattern: /^(?![\d]+$)(?![a-z]+$)(?![A-Z]+$)(?![!<>#$?@%^&*,]+$)[\da-zA-Z!<>#$?@%^&*,]{6,12}$/, message: '至少包含大小写字母、数字和特殊字符其中两种', trigger: 'blur' }
    ],
    sNewPassword: [
        { required: true, message: '请输入确定密码', trigger: 'blur' },
        { min: 6, max: 15, message: '密码长度在 6 到 12 个字符', trigger: 'blur' },
        {
            validator(rule, value, callback) {
                if (value !== updateAccountForm.newPassword) {
                    callback(new Error('两次输入密码不一致!'))
                    return;
                }
                callback();
            },
            trigger: 'blur'
        },
    ],
    address: [
        { required: true, message: '地址为必填项', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '邮箱为必填项', trigger: 'blur' },
        { type: 'email', message: '格式不对', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { len: 11, message: '手机号码长度不对', trigger: 'blur' }
    ]

})
const updateAccountForm = reactive<updateAccountForm>({
    oldPassword: '',
    newPassword: '',
    sNewPassword: ''
})


onMounted(async () => {
    //挂载获取仓库用户信息  userInfo  与仓库接通
    // await userInfoStore.saveUserInfo(uuid)
    userInfo.value = userInfoStore.userInfo
    const res = await findAccount({ uuid })
    userInfo.value = res.data.data
    initTableInfo()
})
const initTableInfo = async () => {
    //获取自己文章展示
    try {
        const { limit, orderDto } = tableInfo
        const data = { orderDto, limit }

        const res = await findArticles(data)
        tableInfo.articles = res.data.data.articles
        tableInfo.total = res.data.data.total
    } catch (error) {
    }
}
//修改密码
const updateAccount = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, error) => {
        if (valid) {
            //校验通过
            const { uuid, account } = userInfoStore.userInfo
            const { oldPassword, newPassword } = updateAccountForm
            const updateAccountDto = { uuid, account, oldPassword, newPassword }
            const res = await editAccount(updateAccountDto)
            const { data } = res
            if (data.code === 200) {
                accountDrawer.value = false
                //修改成功
                ElMessage({
                    message: data.msg,
                    type: 'success',
                })
            }
        }
    })
}
//取消修改表单按钮
const cancelUpdateAccount = (formEl: FormInstance | undefined) => {
    accountDrawer.value = false
    if (!formEl) return
    formEl.resetFields()
}
//修改信息打开Modal
const updateUserInfo = () => {
    dialogFormVisible.value = true;
    //深拷贝对象  ++  响应式
    updateUserInfoForm = toReactive(JSON.parse(JSON.stringify(userInfo.value)))
    updateUserInfoForm.hobbies = updateUserInfoForm.hobbies.map(item => item.name)
}
//修改信息提交
const submitSaveUserInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, error) => {
        if (valid) {
            const { avatar, nickname, gender, birthday, email, phone, address, introduction, hobbies, profession } = updateUserInfoForm
            const newUserInfo = { uuid, avatar, nickname, gender, birthday, email, phone, address, introduction, hobbies, profession }
            const res = await editUserInfo(newUserInfo)
            const { data } = res

            if (data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: data.msg
                })
                //通知仓库更新信息  这里为什么要等待呢  应为需要等待仓库更新完后才再给userInfo赋值
                await userInfoStore.saveUserInfo(data.data.uuid)
                userInfo.value = userInfoStore.userInfo
                dialogFormVisible.value = false
            } else {
                ElMessage({
                    type: 'error',
                    message: data.msg
                })
            }
        } else {
            console.log(error);
        }
    })

}
//添加爱好
const handleClose = (tag: string) => {
    updateUserInfoForm.hobbies.splice(updateUserInfoForm.hobbies.indexOf(tag), 1)
}
const showInput = () => {
    updateUserInfoForm.inputVisible = true
    nextTick(() => {
        InputRef.value!.input!.focus()
    })
}
const handleInputConfirm = () => {
    if (updateUserInfoForm.inputValue) {
        updateUserInfoForm.hobbies.push(updateUserInfoForm.inputValue)
    }
    updateUserInfoForm.inputVisible = false
    updateUserInfoForm.inputValue = ''
}

//上传前规范规格
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    const types = ['image/webp', 'image/jpeg', 'image/png']
    if (!types.includes(rawFile.type)) {
        ElMessage.error('图片仅支持webp，jpg，png三种格式')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}
//上传头像
function uploadIcon(res: any) {
    const { data } = res
    if (data.code === 200) {
        ElNotification({
            title: 'Success',
            message: '上传成功',
            type: 'success',
        })
        updateUserInfoForm.avatar = data.data.imgUrl
    } else {
        ElNotification({
            title: 'Error',
            message: '上传失败',
            type: 'error',
        })
    }
}

//点击标题
const toArticleDetail = (id: number) => {
    router.push({ name: 'article_detail', params: { id } })
}


</script>
<style scoped lang="scss">
.container {
    display: flex;
    // height: 100%;
    .table {
        width: 100%;
    }

    .main-container {
        display: flex;
        justify-content: space-between;
        flex-direction: column;
        width: 100%;
        margin: 0 20px;
    }
}

.aside {
    width: 400px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.text {
    font-size: 14px;
}


.avatar-container {
    width: 100px;
    height: 100px;
    line-height: 100px;
    display: inline-block;

    .img {
        width: 50px;
        height: 50px;
        transform: translateY(30%);
        border-radius: 50%;
        display: inline-block;
    }
}


.item {
    margin-bottom: 18px;
}

.box-card {
    padding: 20px;
    margin-bottom: 20px;
    padding: 50px;
    // min-height: 750px;
}

.edit-btn {
    display: block;
    margin: 0 auto;
} 

.account-btn-container {
    display: flex;
    justify-content: center;
    width: 80%;
} 

.mx-1 {
    margin: 0 3px;
}

//头像
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.introduction-box {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
</style>